function craeteBgRect(obj: egret.DisplayObjectContainer, fillColor = 0, alpha = 0.3): eui.Rect {
	const bg = new eui.Rect();
	bg.fillColor = fillColor;
	fullAlign(bg);
	bg.alpha = alpha;
	obj.addChildAt(bg, 0);
	return bg;
}

type ModalWin = egret.DisplayObject;

class MainModal extends UILayer {
	Main: egret.DisplayObject;

	// 当有obj，bg.visiable=true，点不到之后！
	// 当没有obj，bg.visiable=false
	bg: eui.Rect;

	constructor(Main: egret.DisplayObject) {
		super();
		this.Main = Main;
		this.bg = craeteBgRect(this);
		this.bg.visible = false;
	}

	// 模式窗口
	showModal(obj: ModalWin, effect = '', timems = 100, alpha = 0.3): void {
		// egret.assert(this.numChildren == 0)
		this.touchEnabled = true;
		this.addChild(obj);
		if (this.bg) {
			this.bg.visible = true;
			this.bg.alpha = alpha;
		}

		MainWindow.ins().focus.pushFocus(obj);
		if (effect) {
			setEffectUI(obj, effect, 100);
		}
	}

	doRemoveModal(obj: ModalWin): void {
		// egret.assert(this.numChildren == 1)
		this.removeChild(obj);
		if (this.numChildren === 0 || (this.bg && this.numChildren === 1)) {
			this.touchEnabled = false;
			if (this.bg) {
				this.bg.visible = false;
			}
		}
		// egret.assert(this.numChildren == 0)
		MainWindow.ins().focus.popFocus(obj);
	}

	async removeModal(obj: ModalWin, effect = '', timems = 100): Promise<void> {
		if (effect) {
			await asyncSetEffectUI(obj, effect, timems);
		}
		this.doRemoveModal(obj);
	}

	onEscape(): boolean {
		if (this.numChildren === 0 || (this.bg && this.numChildren === 1)) {
			return false;
		}
		const index = this.numChildren - 1;
		const win = this.getChildAt(index);
		// eslint-disable-next-line prettier/prettier
		if (win["onEsc"]){
			// eslint-disable-next-line prettier/prettier
			win["onEsc"]()
		}
		if (win.parent === this) {
			this.removeModal(win);
		}
		return true;
	}

	closeChild(win: ModalWin): void {
		this.removeModal(win);
	}
}
